import * as mars3d from "mars3d";
import * as Cesium from "mars3d-cesium";
import * as echarts from "echarts";
import useOnemapStore from "@/store/modules/onemap";
let onemapStore = useOnemapStore();
import { gnssRealtime, sideSlopeGnssTrend, getHistoryData, getTrendData } from "@/api/situation";
// import * as turf from "@turf/turf";
import flvjs from "flv.js";
// import WKT from "terraformer-wkt-parser";
const flvPlayers = {}; // 视频实例
class mapUtil {
  mapInstance;
  // 综合态势图层组
  iotGroupLayer;
  // 设备展示图层
  deviceLayer
  constructor (map) {
    if (map) this.mapInstance = map;
    else throw new Error("constructor参数不能为空！");
    // 综合态势图层组
    this.iotGroupLayer = new mars3d.layer.GroupLayer({
      show: true,
    });
    this.mapInstance.addLayer(this.iotGroupLayer);

    // 设备展示图层
    this.deviceLayer = new mars3d.layer.GraphicLayer({
      id: "deviceLayer",
      show: true,
    });

    this.iotGroupLayer.addLayer(this.deviceLayer);
  }
  // 清除图层组中的所有图层上的数据（切换页面使用）并保留图层组中的图层
  clearIotGroupLayer() {
    const layerGroup = this.iotGroupLayer.getLayers()
    if (layerGroup) {
      layerGroup.forEach(childLayer=>{
        if (childLayer.clear) {
          childLayer.clear(); // 例如：PointLayer、GraphicLayer等
        } else if (childLayer.removeAll) {
          childLayer.removeAll(); // 有些图层可能使用removeAll
        }
      })
    }
  }

  // 加载设备列表
  loadGnssData(data, callback, openPidId) {
    const chartId = `chart_${data.id}_${new Date().getTime()}`;
    const tableId = `table_${data.id}_${new Date().getTime()}`;
    let position = [data.longitude, data.latitude];
    const graphic = new mars3d.graphic.BillboardEntity({
      id: `device_${data.id}`,
      attr: data,
      position,
      style: {
        image: "images/deviceIcon/gnss.png",
        scale: 1,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        visibleDepth: false,
        label: {
          font_size: 12,
          text: data.equipName,
          pixelOffsetX: 45,
          pixelOffsetY: -63,
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 3000,
        },
        scale: 0.6,
        clampToGround: true,
      },
    });
    gnssRealtime({
      // '宝宏矿业-BP03' ||
      deviceName: data.equipName,
      openPitId: onemapStore.currentOpenPitInfo.id,
    }).then((gnssData) => {
      // 使用bindPopup方法绑定弹窗
      graphic.bindPopup(() => {
        return `<div class="device-popup-container">
            <div class="device-popup-header">
              <span>设备编号: ${ gnssData.data.deviceName }</span>
            </div>
            <div class="device-info-module">
              <div>
                <div class="device-pos">设备位置：经度:${data.longitude.toFixed(3)}   纬度:${data.latitude.toFixed(3)}</div>
                <div class="device-content">
                  <div>
                    <div>X位移值</div>
                    <div id="slope-data--gnssData-data-x">${
                      gnssData.data.x
                    }</div>
                  </div>
                  <div>
                    <div>Y位移值</div>
                    <div id="slope-data--gnssData-data-y">${
                      gnssData.data.y
                    }</div>
                  </div>
                  <div>
                    <div>H位移</div>
                    <div id="slope-data--gnssData-data-h">${
                      gnssData.data.h
                    }</div>
                  </div>
                </div>
              </div>
            </div>
          
            <div class="chart-module">
              <div id="${chartId}" class="chart-div"></div>
            </div>
          </div>`;
        },
        {
          clampToGround: true,
          closeButton: true,
          autoClose: false,
          className: "mars3d-popup-custom",
        }
      );
    });

    // 监听popup打开事件，初始化图表
    graphic.on(mars3d.EventType.popupOpen, function (e) {
      // graphic.flyTo({ scale: 0.3, pitch: -45 });
      setTimeout(() => {
        initChart(chartId, data);
        gnssRealtime({
          // '宝宏矿业-BP03' ||
          deviceName: data.equipName,
          openPitId: onemapStore.currentOpenPitInfo.id,
        }).then((gnssData) => {
          const idx = document.getElementById("slope-data--gnssData-data-x");
          const idy = document.getElementById("slope-data--gnssData-data-y");
          const idh = document.getElementById("slope-data--gnssData-data-h");
          idx.innerText = gnssData.data.x;
          idy.innerText = gnssData.data.y;
          idh.innerText = gnssData.data.h;
        });
      }, 100);
    });

    this.deviceLayer.addGraphic(graphic);

    // 初始化折线图
    function initChart(chartId, deviceData) {
      // 保持原有的图表初始化代码不变
      const chartDom = document.getElementById(chartId);
      if (!chartDom) {
        console.error("Chart DOM element not found:", chartId);
        return;
      }

      // 使用echarts初始化图表
      const myChart = echarts.init(chartDom);
      // '宝宏矿业-BP03' ||
      sideSlopeGnssTrend({
        deviceName: data.equipName,
        openPitId: onemapStore.currentOpenPitInfo.id,
      }).then((gnssData) => {
        gnssData = gnssData.data;
        const seriesx = gnssData.yrecord.map((item) => item.x);
        const seriesy = gnssData.yrecord.map((item) => item.y);
        const seriesh = gnssData.yrecord.map((item) => item.h);
        const legendData = [
          "x(北)方向变化量",
          "Y(东)方向变化量",
          "H(垂直)方向变化量",
        ];
        const option = {
          title: {
            text: "GNSS位移变化趋势图",
            left: "center",
            textStyle: {
              fontSize: 14,
              color: "#fff",
            },
          },
          tooltip: {
            trigger: "axis",
            backgroundColor: "rgba(10, 20, 40, 0.8)",
            borderColor: "#1e90ff",
            textStyle: {
              color: "#fff",
              fontSize: 10
            },
          },
          legend: {
            data: legendData,
            top: 30,
            textStyle: {
              color: "#fff",
              fontSize: 10
            },
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            top: 70,
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: data.xtime,
            axisLine: {
              lineStyle: {
                color: "#1e4b8f",
              },
            },
            axisLabel: {
              color: "#fff",
              rotate: 40,
              fontSize: 10
            },
          },
          yAxis: {
            type: "value",
            // max: 6, //最大值
            // min: -18, //最小值
            // interval: 3, //间隔
            axisLine: {
              lineStyle: {
                color: "#1e4b8f",
              },
            },
            splitLine: {
              lineStyle: {
                color: "rgba(30, 75, 143, 0.3)",
              },
            },
            axisLabel: {
              color: "#fff",
              fontSize: 10,
              formatter: function (val) {
                //百分比显示
                return val + "mm";
              },
            },
          },

          series: [
            {
              name: "x(北)方向变化量",
              type: "line",
              data: seriesx,
              smooth: true,
              symbol: "none",
              lineStyle: {
                width: 2,
                // color: "#4169E1",
              },
            },
            {
              name: "Y(东)方向变化量",
              type: "line",
              data: seriesy,
              smooth: true,
              symbol: "none",
              lineStyle: {
                width: 2,
                // color: "#4169E1",
              },
            },
            {
              name: "H(垂直)方向变化量",
              type: "line",
              data: seriesh,
              symbol: "none",
              smooth: true,
              lineStyle: {
                width: 2,
                // color: "#4169E1",
              },
            },
          ],
        };

        myChart.setOption(option);

        // 窗口大小变化时重新调整图表大小
        window.addEventListener("resize", function () {
          myChart.resize();
        });
      });
      // 模拟数据 - 参考图片中的空气指数图
    }
  }

  // 加载监控设备
  loadVideoData(data) {
    let position = [data.longitude, data.latitude];
    const graphicImg = new mars3d.graphic.BillboardEntity({
      id: `camera_${data.id}`,
      attr: data,
      position,
      style: {
        image: "images/deviceIcon/monitor.png",
        scale: 1,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        visibleDepth: false,
        label: {
          font_size: 14,
          text: data.equipName,
          pixelOffsetX: 30,
          pixelOffsetY: -63,
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 30000,
        },
        scale: 0.6,
        clampToGround: true,
      },
    });
    this.deviceLayer.addGraphic(graphicImg);
    const options = {
      offsetX: -40,
      offsetY: -20, // 显示Popup的偏移值，是DivGraphic本身的像素高度值
      template: `<div class="marsBlackPanel animation-spaceInDown">
                          <div class="marsBlackPanel-text video-player--wrapper">{content}</div>
                          <span class="mars3d-popup-close-button closeButton" style="color:#fff" >×</span>
                        </div>`,
      horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
      verticalOrigin: Cesium.VerticalOrigin.CENTER,
    };
    const content = `
      <video id="camera_${data.id}" class="video-player" muted controls="true"></video>
    `;

    graphicImg.bindPopup(content, options);

    graphicImg.on(mars3d.EventType.popupOpen, (e) => {
      // 延迟一点时间确保DOM已经渲染
      const initVideoPlayer = (videoId, videoUrl) => {
        const videoElement = document.getElementById('camera_'+videoId);
        if (!videoElement) {
          console.error(`未找到ID为${videoId}的视频元素`);
          return;
        }

        if (flvjs.isSupported()) {
          // 如果已存在播放器实例，先销毁
          if (flvPlayers[videoId]) {
            flvPlayers[videoId].destroy();
          }

          // 创建flv播放器
          const flvPlayer = flvjs.createPlayer({
            type: "flv",
            url: videoUrl,
            isLive: true,
            hasAudio: false,
            hasVideo: true,
            cors: true,
          });

          flvPlayer.attachMediaElement(videoElement);
          flvPlayer.load();

          setTimeout(() => {
            flvPlayer.play.bind(flvPlayer)();
          }, 1000);

          // 添加更多事件监听以便调试
          flvPlayer.on(flvjs.Events.LOADING_COMPLETE, () => {
            console.log(`${videoId} 加载完成`);
          });

          flvPlayer.on(flvjs.Events.MEDIA_INFO, (mediaInfo) => {});

          // 存储播放器实例
          flvPlayers[videoId] = flvPlayer;

          // 添加事件监听
          videoElement.addEventListener("play", () => {});

          videoElement.addEventListener("pause", () => {
            console.log(`${videoId} 暂停播放`);
          });

          videoElement.addEventListener("error", (e) => {
            console.error(`${videoId} 视频元素错误:`, e);
          });
        } else {
          console.error("您的浏览器不支持FLV.js");
        }
      };

      initVideoPlayer(data.id, data.videoUrl);
    });

    graphicImg.on(mars3d.EventType.popupClose, (e) => {
      // 清理播放器资源
      if (flvPlayers[data.id]) {
        try {
          const player = flvPlayers[data.id];
          if (player) {
            player.pause();
            player.unload();
            player.detachMediaElement();
            player.destroy();
            delete flvPlayers[data.id];
          }
        } catch (err) {
          console.error("销毁播放器时出错:", err);
        }
      }
    });
  }

  // 加载监控设备
  loadDustData(data, pm10T, pm25T, noiseT) {
    const chartId = `chart_${data.id}_${new Date().getTime()}`;
    const tableId = `table_${data.id}_${new Date().getTime()}`;
    let position = [data.longitude, data.latitude];
    const graphic = new mars3d.graphic.BillboardEntity({
      id: `device_${data.deviceId}`,
      attr: data,
      position,
      style: {
        image: "images/deviceIcon/dust.png",
        scale: 1,
        opacity: 0.85,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        visibleDepth: false,
        label: {
          font_size: 14,
          text: '环境设备',
          pixelOffsetY: -64,
          pixelOffsetX: 56,
          distanceDisplayCondition: true,
          distanceDisplayCondition_far: 30000,
        },
        scale: 0.6,
        clampToGround: true,
        pixelOffsetX: 22,
        pixelOffsetY: -2,
      },
    });
    graphic.bindPopup(
      () => {
        return `<div class="device-popup-container">
      <div class="device-popup-header">
        <div style="display:flex; align-items:center;">
          <span style="display:inline-block; width:8px; height:8px; border-radius:50%; background:#1e90ff; margin-right:8px;"></span>
          <span style="font-weight:bold; font-size:16px; color:#fff;">设备数据</span>
        </div>
      </div>
      
      <div class="device-info-module">
        <div style="margin-bottom:10px; font-size:14px; display:flex;">
          <span style="color:#8cc8ff; margin-right:10px;">设备ID:</span>
          <span>${data.id}</span>
        </div>
        <div style="margin-bottom:10px; font-size:14px; display:flex;">
          <span style="color:#8cc8ff; margin-right:10px;">设备状态:</span>
          <span style="background:#00b578; color:#fff; padding:2px 8px; border-radius:2px; font-size:12px;">${
            data.onlineStatus == 1 ? "在线" : "离线"
          }</span>
        </div>
        <div style="margin-bottom:10px; font-size:14px; display:flex;">
          <span style="color:#8cc8ff; margin-right:10px;">安装位置经纬度:</span>
          <span>${data.longitude},${data.latitude}</span>
        </div>
        
        
      
      <div class="chart-module">
        <div style="display:flex; align-items:center; margin-bottom:10px;">
          <span style="display:inline-block; width:8px; height:8px; border-radius:50%; background:#1e90ff; margin-right:8px;"></span>
          <span style="font-weight:bold; font-size:14px; color:#fff;">变化趋势图</span>
        </div>
        <div id="${chartId}" class="chart-div"></div>
      </div>`;
      },
      {
        clampToGround: true,
        closeButton: true,
        autoClose: false,
        className: "mars3d-popup-custom",
      }
    );
    // 监听popup打开事件，初始化图表
    graphic.on(mars3d.EventType.popupOpen, function (e) {
      console.log("popup opened, initializing chart", data, e);
      graphic.flyTo({
        scale: 0.01,
        pitch: -95,
        heading: 20,
        radius: 100000,
        complete: () => {},
      });
      setTimeout(() => {
        initChart(chartId, tableId);
      }, 100);
    });

    this.deviceLayer.addGraphic(graphic);

    // 初始化折线图
    function initChart(chartId, tableId) {
      console.log("initChart", chartId);
      const chartDom = document.getElementById(chartId);
      if (!chartDom) {
        console.error("Chart DOM element not found:", chartId);
        return;
      }

      // 使用echarts初始化图表
      const myChart = echarts.init(chartDom);
      getTrendData({
        deviceId: data.id,
        openPitId: onemapStore.currentOpenPitInfo.id,
      }).then((res) => {
        const chartData = res.data;
        const pm25 = chartData.yrecord.map((item) => item.pm25);
        const pm10 = chartData.yrecord.map((item) => item.pm10);
        const wendu = chartData.yrecord.map((item) => item.tem);
        const noise = chartData.yrecord.map((item) => item.noise);
        const hum = chartData.yrecord.map((item) => item.hum);
        // const
        // 模拟数据 - 参考图片中的环境监测趋势图
        const option = {
          tooltip: {
            trigger: "axis",
            backgroundColor: "rgba(10, 20, 40, 0.8)",
            borderColor: "#1e90ff",
            textStyle: {
              color: "#fff",
            },
          },
          legend: {
            data: ["温度", "湿度", "噪音", "PM10", "PM2.5"],
            top: 0,
            textStyle: {
              color: "#fff",
              fontSize: 10,
            },
            itemWidth: 12,
            itemHeight: 8,
          },
          grid: {
            left: "3%",
            right: "4%",
            bottom: "3%",
            top: 30,
            containLabel: true,
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            data: chartData.xtime,
            axisLine: {
              lineStyle: {
                color: "#1e4b8f",
              },
            },
            axisLabel: {
              color: "#fff",
              fontSize: 10,
            },
          },
          yAxis: {
            type: "value",
            max: 100,
            min: -20,
            interval: 20,
            axisLine: {
              lineStyle: {
                color: "#1e4b8f",
              },
            },
            splitLine: {
              lineStyle: {
                color: "rgba(30, 75, 143, 0.3)",
              },
            },
            axisLabel: {
              color: "#fff",
              fontSize: 10,
            },
          },
          series: [
            {
              name: "温度",
              type: "line",
              data: wendu,
              smooth: true,
              symbol: "none",
              lineStyle: {
                width: 2,
                color: "#4169E1",
              },
            },
            {
              name: "湿度",
              type: "line",
              data: hum,
              smooth: true,
              symbol: "none",
              lineStyle: {
                width: 2,
                color: "#90EE90",
              },
            },
            {
              name: "噪音",
              type: "line",
              data: noise,
              smooth: true,
              symbol: "none",
              lineStyle: {
                width: 2,
                color: "#FFD700",
              },
            },
            {
              name: "PM10",
              type: "line",
              data: pm10,
              smooth: true,
              symbol: "none",
              lineStyle: {
                width: 2,
                color: "#FF6347",
              },
            },
            {
              name: "PM2.5",
              type: "line",
              data: pm25,
              smooth: true,
              symbol: "none",
              lineStyle: {
                width: 2,
                color: "#87CEEB",
              },
            },
          ],
        };

        myChart.setOption(option);

        // 窗口大小变化时重新调整图表大小
        window.addEventListener("resize", function () {
          myChart.resize();
        });
      });

      getHistoryData({
        deviceId: data.id,
        openPitId: onemapStore.currentOpenPitInfo.id,
      }).then((res) => {
        let historyListStr = "";
        res.data.forEach((item) => {
          historyListStr += `
          <tr style="text-align:center;">
          <td style="padding:8px;">${item.pm25}</td>
          <td style="padding:8px;">${item.pm10}</td>
          <td style="padding:8px;">${item.noise}</td>
          <td style="padding:8px;">${item.tem}</td>
          <td style="padding:8px;">${item.hum}</td>
          <td style="padding:8px;">${item.time}</td>
          </tr>
          `;
        });

        // 获取 id 为 table2 的 table 元素
        const table = document.getElementById(tableId);
        // 获取 table 元素中的 tbody 元素
        const tbody = table.getElementsByTagName("tbody")[0];

        tbody.innerHTML = historyListStr;
      });
    }
  }

  // 清除设备layer上的数据
  claerDeviceLayer() {
    if (this.deviceLayer) {
      this.deviceLayer.clear();
    }
  }

}

export default mapUtil;
